﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shsc.Net.Common.Dto;

namespace Shsc.Net.Common.Logic.Impl
{
    public abstract class AbstractPagingBaseLogicImpl : PagingBaseLogic
    {
        #region PagingBaseLogic 成员

        public List<PagingBaseInspDto> Search(PagingBaseDto baseDto)
        {
            PagingBaseCondDto condDto = baseDto.CondDto;
            condDto.Limit = baseDto.PageSize;
            condDto.Offset = 0;
            baseDto.CurrentPageIndex = 0;
            List<PagingBaseInspDto> lisResult = searchData(baseDto, condDto);
            return lisResult;
        }

        public List<PagingBaseInspDto> Paging(PagingBaseDto baseDto)
        {
            prepareBeforeSrch(baseDto);
            PagingBaseCondDto condDto = baseDto.CondDto;
            List<PagingBaseInspDto> lisResult = searchData(baseDto, condDto);
            prepareAfterSrch(baseDto, lisResult);
            return lisResult;
        }

        protected void prepareBeforeSrch(PagingBaseDto baseDto)
        {
            int pageSize = baseDto.PageSize;
            int currentPage = baseDto.CurrentPageIndex;

            baseDto.CondDto.Offset = (currentPage - 1) * pageSize;
            baseDto.CondDto.Limit = pageSize;
        }

        protected void prepareAfterSrch(PagingBaseDto baseDto,
            List<PagingBaseInspDto> lisResult)
        {
            if (lisResult == null || lisResult.Count == 0)
            {
                baseDto.CurrentPageIndex = 0;
                return;
            }

            int size = lisResult.Count;
            int totalRows = baseDto.CondDto.Count;

            if (totalRows == 0)
            {
                totalRows = size;
            }

            baseDto.AllCount = totalRows;
            baseDto.AllPages = totalRows / baseDto.PageSize;
        }

        protected abstract List<PagingBaseInspDto> searchData(PagingBaseDto baseDto,
            PagingBaseCondDto condDto);

        #endregion
    }
}
